package com.vodone.v1pin.user.model
{
	import com.vodone.v1pin.core.model.MainModelLocator;
	import com.vodone.v1pin.core.utils.GoodsUtil;
	import com.vodone.v1pin.user.delegate.UserBagDelegate;
	import com.vodone.v1pin.user.vo.AddressTimeItemVO;
	import com.vodone.v1pin.user.vo.CouponSendVO;
	import com.vodone.v1pin.user.vo.GoodsKCVO;
	import com.vodone.v1pin.user.vo.ItemDetailVO;
	import com.vodone.v1pin.user.vo.ItemVO;
	import com.vodone.v1pin.user.vo.MyGoodsListVO;
	import com.vodone.v1pin.user.vo.MyGoodsVO;
	import com.vodone.v1pin.userInfo.delegate.AddressDelegate;
	import com.vodone.v1pin.userInfo.delegate.AddressUtil;
	import com.vodone.v1pin.userInfo.event.CloseWindowEvent;
	import com.vodone.v1pin.userInfo.vo.AddressVO;
	import com.vodone.v1pin.userInfo.vo.CouponVO;
	
	import flash.utils.Dictionary;
	
	import mx.collections.ArrayCollection;
	import mx.preloaders.Preloader;

	[Bindable]
	public class BagModelLocator
	{
		public static const MYBAG:int = 0;
		public static const NOTIC:int = 1; 
		
		public static const MYBAGFIRST:int = 0;
		public static const CONFIRM:int = 1;
		public static const ADDNEWADDRESS:int = 2;
		public static const CONFIRMORDER:int = 3;
		public static const PAY:int = 4;
		public static const SUCCESS:int = 5;
		/**
		 * 购物车当前现实是购物流程，还是成功页面 
		 */
		public var myBagControlOrResult:int = 0;
		
		/**
		 * 购物车当前现实是购物流程页面索引 
		 */
		public var myBagControlIndex:int = 0;
		
		/**
		 * 用户购物车物品 
		 */		
		public var myGoodList:ArrayCollection;
		
		/**
		 * 用户选择支付方式
		 */		
		public var addressTimeList:ArrayCollection = new ArrayCollection([{"label":"双休日，假日送货（工作日不用送）","index":1},
																		{"label":"工作日送货（双休日，假日不用送）","index":2},
																		{"label":"工作日，双休日与假日均可送货","index":3}]);;
		/**
		 * 用户确认的物品 
		 */		
		public var myConfirmGoodList:ArrayCollection;
		
		/**
		 * 用户地址
		 */		
		public var myAddressList:ArrayCollection;
		
		/**
		 * 用户当前选中地址
		 */		
		public var currentAddress:AddressVO;
		
		/**
		 * 用户当前红包
		 */		
		public var couponList:ArrayCollection;
		
		/**
		 * 用户当前红包
		 */		
		public var currentRedCardIndex:int;
		/**
		 * 用户当前红包
		 */		
		public var currentRedCard:CouponVO;
		/**
		 * 用户当前订单号
		 */		
		public var userOrderId:String;
		
		/**
		 * 用户当前支付方式
		 */		
		public var userOrderType:String;
		
		/**
		 * 用户当前送货方式
		 */		
		public var sendGoodsTypeObject:AddressTimeItemVO = addressTimeList.getItemAt(0) as AddressTimeItemVO;
		
		/**
		 * 用户当前银行编号 0银行汇款，2支付宝，其他银行编号
		 */		
		public var orderpay:String;
		
		
		/**
		 * 用户当前订单金额
		 */		
		public var orderMoney:Number;
		
		/**
		 * v1价总额 
		 */		
		public var totalAmount:Number = 0;
		
		/**
		 * 优惠卷优惠总金额 
		 */		
		public var totalCoupAmount:Number = 0;
		
		/**
		 * 折扣价 
		 */		
		public var disCountAmount:Number = 0;
		
		/**
		 * 当前使用的至尊卡
		 */		
		public var currentGiftCard:ArrayCollection;
		
		/**
		 * 生成订单所有物品
		 */		
		public var sendGoods:Array = [];
		
		/**
		 * 显示等待支付成功还是支付失败
		 */		
		public var noticIndex:int = 0;
		
		/**
		 * 是否保留当前弹出框状态
		 */		
		public var keep:Boolean = false;
		
		public function getAddressList( b:Boolean = true ):void
		{
			if(MainModelLocator.getInstance().userLoginVO.isLogin){
				if( b ){
					AddressDelegate.getAddressList(addressResultHandler);
				}else{
					AddressDelegate.getAddressList(addressResultHandlerNotSetDefault);
				}
			}
		}
		
		public function addressResultHandlerNotSetDefault(obj:Object):void
		{
			if(obj && obj["message"] && obj["message"]["code"] == 0)
			{
				if(obj.hasOwnProperty("data"))
				{
					var listData:ArrayCollection = AddressUtil.getAddressListFromObj(obj["data"]);
					if( listData.length > 0 ){
						myAddressList = listData;
						myAddressList.refresh();
					}
				}
			}
		}
		
		public function addressResultHandler(obj:Object):void
		{
			BagModelLocator.getInstance().parasAddress( obj );
		}
		
		/**
		 * 用户直接购买的物品id 
		 */		
		public var curBuyId:String;
		
		public function confirmCurrentGoods(id:String):void
		{
			goodsDict = new Dictionary();
			var list:Array = [];
			goodsDict[id] = 1;
			list.push(id);
			UserBagDelegate.getBagGoods( myGoodsResultHandler1 , list , faultHandler );
		}
		
		public function myGoodsResultHandler1( obj:Object ):void
		{
			BagModelLocator.getInstance().myGoodList = (new MyGoodsListVO( obj )).goodsList;
			BagModelLocator.getInstance().totalAmount = 0;
			BagModelLocator.getInstance().disCountAmount = 0;
			var len:int = BagModelLocator.getInstance().myGoodList.length;
			for(var i:uint=0;i<len;i++){
				var goods:MyGoodsVO = BagModelLocator.getInstance().myGoodList.getItemAt(i) as MyGoodsVO;
				goods.count = goodsDict[goods.id];
				
				if( goods.isSelected )
				{
					BagModelLocator.getInstance().totalAmount += goods.v1Price * goods.count;
					BagModelLocator.getInstance().disCountAmount +=( goods.price - goods.v1Price) * goods.count;
				}
				
			}
			confirmGoods();
			if( myAddressList && myAddressList.length > 0 ){
				myBagControlIndex = BagModelLocator.CONFIRMORDER;
			}else{
				myBagControlIndex = BagModelLocator.CONFIRM;
			}
			//			new CloseWindowEvent(CloseWindowEvent.CONFIRM_GOODS).dispatch();
		}
		
		public function parasAddress( obj:Object ):void
		{
			if(obj && obj["message"] && obj["message"]["code"] == 0)
			{
				if(obj.hasOwnProperty("data"))
				{
					var listData:ArrayCollection = AddressUtil.getAddressListFromObj(obj["data"]);
					if( listData.length > 0 ){
						myAddressList = listData;
						currentAddress = listData.getItemAt(0) as AddressVO;
					}
					var len:int = listData.length;
					for( var i:uint;i<len;i++){
						if((listData.getItemAt(i) as AddressVO).isDefault == 1 ){
							currentAddress = listData.getItemAt(i) as AddressVO;
							myAddressList.removeItemAt( i );
							myAddressList.addItemAt( currentAddress , 0 );
							myAddressList.refresh();
							return;
							break;
						}
					}
					
				}
			}
		}
		
		/**
		 * 从新计算价钱 
		 * 
		 */		
		public function caculateMoney():void
		{
			totalAmount = 0;
			disCountAmount = 0;
			var len:int = myGoodList.length;
			for(var i:uint=0;i<len;i++){
				var goods:MyGoodsVO = myGoodList.getItemAt(i) as MyGoodsVO;
				if( goods.isSelected )
				{
					totalAmount += goods.v1Price * goods.count;
					disCountAmount +=( goods.price - goods.v1Price) * goods.count;
				}
				
			}
		}
		
		/**
		 * 用户世界要买的商品
		 */		
		public function confirmGoods():void
		{
			var dic:Dictionary = new Dictionary();
			sendGoods = [];
			if(myGoodList == null) return;
			var len:int = myGoodList.length;
			var list:ArrayCollection = new ArrayCollection();
			
			for(var i:uint=0;i<len;i++){
				var goods:MyGoodsVO = myGoodList.getItemAt(i) as MyGoodsVO;
				if( goods.isSelected )
				{
					if(dic[goods.providerId] == undefined){
						dic[goods.providerId] = new ArrayCollection();
						ArrayCollection(dic[goods.providerId]).addItem( goods );
					}else{
						ArrayCollection(dic[goods.providerId]).addItem( goods );
					}
					
				}
			}
			
			var temp:ArrayCollection = new ArrayCollection();
			
			for( var j:String in dic ){
				temp.addItem( dic[j] );
				
				var item:ItemVO = new ItemVO();
				item.shopID = int(j);
				item.ItemDetailVO = [];
				
				for( var z:uint=0;z<dic[j].length;z++){
					var itemDetail:ItemDetailVO = new ItemDetailVO();
					var tg:MyGoodsVO = (dic[j] as ArrayCollection).getItemAt( z ) as MyGoodsVO;
					itemDetail.itemID = tg.id;
					itemDetail.itemNum = tg.count;
					itemDetail.price = tg.v1Price;
					item.ItemDetailVO.push( itemDetail );
				}
				
				sendGoods.push( item );
			}
			myConfirmGoodList = temp;
			
		}
		
		public function clearAll():void
		{
			myGoodList = null;
			currentRedCard = null;
			currentRedCardIndex = -1;
			noticIndex = 0;
			myAddressList = null;
			currentAddress = null;
			couponList = null;
			currentAddress = null;
			userOrderId = "";
			orderMoney = 0;
			totalAmount = 0;
			totalCoupAmount = 0;
			disCountAmount = 0;
			curBuyId = "";
//			userOrderType = "";
//			orderpay = "";
			myBagControlOrResult = MYBAG;
			myBagControlIndex = MYBAGFIRST;
			sendGoodsTypeObject = addressTimeList.getItemAt(0) as AddressTimeItemVO;
			sendGoods = [];
		}
		
		public var goodsLen:int = 0;
		
		private var goodsDict:Dictionary;
		public function reFreshMyGoods():int
		{
			
			goodsDict = new Dictionary();
			var obj:Object = GoodsUtil.getGoods();
			var list:Array = [];
			for( var i:String in obj ){
				list.push(i);
				goodsDict[i] = obj[i].count;
			}
			
			
			goodsLen = list.length;
			if( list.length == 0 ) {
				BagModelLocator.getInstance().myGoodList = new ArrayCollection();
				BagModelLocator.getInstance().totalAmount = 0;
				BagModelLocator.getInstance().disCountAmount = 0;
				return 0;
			}
			UserBagDelegate.getBagGoods( myGoodsResultHandler , list , faultHandler );
			return list.length;
		}
		
		public var funcDict:Dictionary = new Dictionary();
		public function checkGoodsKC( id:String , fun:Function ):void
		{
			funcDict[id] = fun;
			UserBagDelegate.getBagGoodsKC( myGoodsKCResultHandler , id , faultHandler );
		}
		
		private function myGoodsKCResultHandler( obj:Object ):void
		{
			var kcVO:GoodsKCVO = new GoodsKCVO(obj);
			if(funcDict[kcVO.id])
			{
				funcDict[kcVO.id]( kcVO );
			}
		}
		
		private function faultHandler( obj:Object ):void
		{
		}
		
		public function myGoodsResultHandler( obj:Object ):void
		{
			
			
			
			BagModelLocator.getInstance().myGoodList = (new MyGoodsListVO( obj )).goodsList;
			BagModelLocator.getInstance().totalAmount = 0;
			BagModelLocator.getInstance().disCountAmount = 0;
			var len:int = BagModelLocator.getInstance().myGoodList.length;
			for(var i:uint=0;i<len;i++){
				var goods:MyGoodsVO = BagModelLocator.getInstance().myGoodList.getItemAt(i) as MyGoodsVO;
				goods.count = goodsDict[goods.id];
				
				if( goods.isSelected )
				{
					BagModelLocator.getInstance().totalAmount += goods.v1Price * goods.count;
					BagModelLocator.getInstance().disCountAmount +=( goods.price - goods.v1Price) * goods.count;
				}
				
			}
			
//			new CloseWindowEvent(CloseWindowEvent.CONFIRM_GOODS).dispatch();
		}
		
		public function clearSendGoods():void
		{
			var len:int = sendGoods.length;
			for( var i:uint = 0; i<len; i++ ){
				var item:ItemVO = sendGoods[i] as ItemVO;
				var len1:int = item.ItemDetailVO.length;
				for( var j:uint =0; j<len1; j++ ){
					var itemD:ItemDetailVO = item.ItemDetailVO[j] as ItemDetailVO;
					GoodsUtil.deleteGoods( String(itemD.itemID) , 1 ,true );
				}
			}
			reFreshMyGoods();
		}
		
		private static var _instance:BagModelLocator;

		public function BagModelLocator()
		{
			if (null != _instance)
			{
				return;
			}
		}

		public static function getInstance():BagModelLocator
		{
			if (_instance == null)
			{
				_instance = new BagModelLocator();
			}
			return _instance;
		}

	}
}